﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using log4net;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.CloudCard;
using Matrix.MaKaYunShang.BLL.WxInterfaceFunc;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;
using Newtonsoft.Json;

namespace Matrix.MaKaYunShang.ApiService.Controllers
{
    /// <summary>
    /// 第三方访问 api
    /// </summary>
    public class ThirdController : BaseApiController
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(ThirdController));
        private readonly CloudCardBll _cloudCardBll = new CloudCardBll();

        #region 固定二维码抽奖 Action

        /// <summary>
        ///  固定二维码抽奖
        /// </summary>
        /// <param name="openId">OpenId</param>
        /// <param name="unionid">unionid</param>
        /// <param name="thirdCode">第三方PjCode</param>
        /// <param name="longitude">经度</param>
        /// <param name="latitude">纬度</param>
        /// <param name="verifyCode">(openId+mcId+longitude+latitude) Encrypt加密</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public async Task<Result<List<CloudCards>>> FixedQrCodeDraw(string openId, string unionid, string thirdCode, string longitude, string latitude, string verifyCode)
        {
            _fileLog.Info("ThirdController | FixedQrCodeDraw | Scan Url:api/Third/FixedQrCodeDraw?openId=" + openId + "&unionid=" + unionid + "&thirdCode=" + thirdCode + "&longitude=" + longitude + "&longitude=" + longitude + "&latitude=" + latitude + "&verifyCode=" + verifyCode);
            var dtTime = DateTime.Now;
            #region 权限和加密验证
            var checkResult = CheckPermission("ThirdController | FixedQrCodeDraw");
            if (!checkResult.Status)
            {
                return new Result<List<CloudCards>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null,
                    StatusCode = (int)CommonEnum.ApiStatusCode.接口权限校验失败
                };
            }

            try
            {
                var strSouceToEncode = openId + unionid + thirdCode + longitude + latitude;
                var strLocalEncodeResult = EncryptionLib.Encrypt(strSouceToEncode, Encoding.UTF8);
                if (strLocalEncodeResult != null && strLocalEncodeResult != verifyCode)
                {
                    _fileLog.Error("ThirdController | FixedQrCodeDraw | Error: Invalid verify code.");
                    return new Result<List<CloudCards>>
                    {
                        Status = false,
                        Message = "Invalid verify verifyCode",
                        Data = null,
                        StatusCode = (int)CommonEnum.ApiStatusCode.参数格式错误
                    };
                }

            #endregion
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["IsThirdShowCard"]))
                {
                    return new Result<List<CloudCards>>
                    {
                        Status = false,
                        Message = "未开启卡劵查询",
                        Data = null,
                        StatusCode = (int)CommonEnum.ApiStatusCode.未开启第三方卡劵查询
                    };
                }
                #region 验证商家和消费者信息
                var mykProjectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcId);
                if (mykProjectInfo == null || mykProjectInfo.IsDelete ||
                        string.IsNullOrWhiteSpace(mykProjectInfo.PjMcId) ||
                        string.IsNullOrWhiteSpace(mykProjectInfo.PjSecret))
                {
                    return new Result<List<CloudCards>>
                    {
                        Status = false,
                        Message = "不能提供服务给调用发券",
                        Data = null,
                        StatusCode = (int)CommonEnum.ApiStatusCode.无效McId或OPENID
                    };
                }

                var wechatUserInfo = GetMxApiWechatUserInfoByuinionId(unionid, MkysMcId);
                if (wechatUserInfo == null)
                {
                    var matrixCloudProjectInfo = MatrixCloudProjectInfoBLL.Instance.GetModelByPjCode(thirdCode);
                    if (matrixCloudProjectInfo == null)
                    {
                        return new Result<List<CloudCards>>
                        {
                            Status = false,
                            Message = "不能提供服务给调用发券",
                            Data = null,
                            StatusCode = (int)CommonEnum.ApiStatusCode.无效McId或OPENID
                        };
                    }
                    var thirdProjectInfo = GetCurrentMatrixCloudProjectInfo(matrixCloudProjectInfo.PjMcId);
                    if (thirdProjectInfo == null || thirdProjectInfo.IsDelete ||
                        string.IsNullOrWhiteSpace(thirdProjectInfo.PjMcId) ||
                        string.IsNullOrWhiteSpace(thirdProjectInfo.PjSecret))
                    {
                        return new Result<List<CloudCards>>
                        {
                            Status = false,
                            Message = "该调用方不可发券",
                            Data = null,
                            StatusCode = (int)CommonEnum.ApiStatusCode.无效McId或OPENID
                        };
                    }

                    //无码云卡用户信息
                    var thirdWechatUserInfo = GetMxApiWechatUserInfoByuinionId(unionid, thirdProjectInfo.PjMcId);
                    if (thirdWechatUserInfo == null)
                    {
                        var resultWechatUserInfo =
                            MatrixCloudCenterInterFuncBllObj.SyncWechatUserFullInfoFromWechatToMatrixCloud(openId,
                                thirdProjectInfo.PjMcId, thirdProjectInfo.PjSecret);

                        if (resultWechatUserInfo == null || !resultWechatUserInfo.Status ||
                            resultWechatUserInfo.Data == null)
                        {
                            return new Result<List<CloudCards>>
                            {
                                Status = false,
                                Message = "无效用户信息",
                                Data = null,
                                StatusCode = (int)CommonEnum.ApiStatusCode.用户信息错误
                            };
                        }
                        thirdWechatUserInfo = resultWechatUserInfo.Data;
                    }
                    //第三方微信用户未使用码云卡系统则无用户ID，特定使用指定字符便于用户发送码云卡券以及正式使用时进行更新
                    thirdWechatUserInfo.OpenId = "#YMCCTOFU#" + thirdWechatUserInfo.WechatUserId;
                    thirdWechatUserInfo.UnSubscribeTime = Convert.ToDateTime("1900-01-01 00:00:00");

                    //TODO: 过阵子修改为以下正确代码
                    /*
                    thirdWechatUserInfo.Subscribe = false;
                    thirdWechatUserInfo.SubscribeTime = Convert.ToDateTime("1900-01-01 00:00:00");
                     */

                    //TODO:过阵子删除以下一行正确代码
                    thirdWechatUserInfo.SubscribeTime = DateTime.Now;

                    var nWechatUserId = thirdWechatUserInfo.Id;
                    thirdWechatUserInfo.WechatUserId = thirdWechatUserInfo.Id;
                    thirdWechatUserInfo.WechatInfoId = mykProjectInfo.WechatInfoId;
                    var resultSaved = MatrixCloudCenterInterFuncBllObj.SaveWechatInfoUser(thirdWechatUserInfo,
                        mykProjectInfo.PjMcId, mykProjectInfo.PjSecret);
                    if (resultSaved == null || !resultSaved.Status)
                    {
                        return new Result<List<CloudCards>>
                        {
                            Status = false,
                            Message = "该调用方的微信用户不可发券",
                            Data = null,
                            StatusCode = (int)CommonEnum.ApiStatusCode.用户信息错误
                        };
                    }
                    thirdWechatUserInfo.WiuId = resultSaved.Data;

                    wechatUserInfo = thirdWechatUserInfo;
                    wechatUserInfo.Id = nWechatUserId;
                }

                var consumer = ConsumerBLL.Instance.GetConsumerInfoByMxWechatInfoUserId(wechatUserInfo.WiuId);
                if (consumer == null || consumer.Id < 1)
                {
                    var newConsumer = new Consumer
                    {
                        MxProjectInfoId = mykProjectInfo.Id,
                        MxWechatInfoUserId = wechatUserInfo.WiuId,
                        Avatar = wechatUserInfo.Headimgurl,
                        NickName = wechatUserInfo.NickName,
                        RealName = wechatUserInfo.RealName,
                        Mobile = wechatUserInfo.Mobile,
                        Sex = int.Parse(wechatUserInfo.Sex),
                        RegTime = DateTime.Now,
                        IpAddress = IpHelper.IPAddress,
                        ShopAccountId = 0,
                        ShopId = 0,
                        Birth = Convert.ToDateTime("1970-01-01 00:00:00"),
                        IsDelete = false
                    };

                    var nConsumerId = ConsumerBLL.Instance.Add(newConsumer);

                    if (nConsumerId == 0)
                    {
                        return new Result<List<CloudCards>>
                        {
                            Data = null,
                            Message = "不能添加新用户",
                            Status = false
                        };
                    }
                    consumer = newConsumer;
                    consumer.Id = nConsumerId;
                }

                var fixedQrCode = string.Empty;
                // 验证商户信息是否合法
                if (FixedCouponShopId > 0)
                {
                    var shop = ShopsBLL.Instance.GetModel(FixedCouponShopId);
                    if (shop == null || shop.Enabled == false)
                    {
                        _fileLog.Error("ThirdController | FixedQrCodeDraw |商家无效 code码无效,shopId=" + FixedCouponShopId);
                        return new Result<List<CloudCards>>
                        {
                            Status = false,
                            Message = "商家无效",
                            Data = null,
                            StatusCode = (int)CommonEnum.ApiStatusCode.店铺信息错误
                        };
                    }
                    if (shop.CanSendCard == false)
                    {
                        _fileLog.Info("ThirdController | FixedQrCodeDraw | 商家未开启扫码功能");
                        return new Result<List<CloudCards>>
                        {
                            Status = false,
                            Message = "商家未开启扫码功能",
                            Data = null,
                            StatusCode = (int)CommonEnum.ApiStatusCode.商家未开启扫码功能
                        };
                    }
                    if (string.IsNullOrEmpty(fixedQrCode))
                    {
                        fixedQrCode = ConfigurationManager.AppSettings["WebUrl"] + "/mkys/market/web/userCenter/drawCard/?Id=" + EncryptionLib.Encrypt(FixedCouponShopId.ToString());
                    }
                }
                #endregion

                #region 验证二维码
                var model = ScanEventBLL.Instance.GetModelByScanQrContent(fixedQrCode, consumer.Id);//用户扫码数量
                if (model != null && model.ScanQrContent == fixedQrCode)
                {
                    if (model.FailScanTime > DateTime.Now && model.IsReceive == false)
                    {
                        model.ScanTime = DateTime.Now;
                        ScanEventBLL.Instance.Update(model);
                        return await LuckDraw(consumer.Id, 0);
                    }
                    if (model.ScanTime.AddMinutes(SysConfig != null ? SysConfig.FixedQrCodeScanTime : 60 * 24) > DateTime.Now)
                    {
                        _fileLog.Error("CloudCardController | FixedQrCodeDraw | 验证二维码code码无效");
                        return new Result<List<CloudCards>>
                        {
                            Status = false,
                            Message = "请稍后再领取",
                            Data = null,
                            StatusCode = (int)CommonEnum.ApiStatusCode.无效二维码
                        };
                    }
                }
                #endregion

                #region 扫一扫记录
                var scanEvent = new ScanEvent
                {
                    ScanTime = dtTime,
                    ConsumerId = consumer.Id,
                    ScanSource = (int)CloudCardEnum.ScanEventScanSource.第三方接口请求,
                    ShopId = FixedCouponShopId,
                    ScanQrContent = fixedQrCode,
                    Longitude = longitude,
                    Latitude = latitude,
                    UserId = consumer.Id,
                    IsReceive = false,
                    Ip = IpHelper.IPAddress,
                    FailScanTime = dtTime.AddHours(FailScanTime)
                };
                int returnId = ScanEventBLL.Instance.Add(scanEvent);
                if (returnId < 1)
                {
                    _fileLog.Info("ThirdController | FixedQrCodeDraw | 卡卷记录添加错误");
                    return new Result<List<CloudCards>>
                    {
                        Status = false,
                        Message = "扫码记录添加错误",
                        Data = null,
                        StatusCode = (int)CommonEnum.ApiStatusCode.系统错误
                    };
                }
                #endregion
                return await LuckDraw(consumer.Id, returnId);
            }
            catch (Exception ex)
            {
                _fileLog.Error("ThirdController | FixedQrCodeDraw | 第三方发送卡券失败 " + ex.Message + ex.StackTrace);
                return new Result<List<CloudCards>>
                {
                    Status = false,
                    Message = "第三方发送卡券失败 " + ex.Message,
                    Data = null,
                    StatusCode = (int)CommonEnum.ApiStatusCode.未中奖
                };
            }
        }
        #endregion

        #region 抽取奖品

        /// <summary>
        /// 抽奖业务
        /// </summary>
        /// <param name="consumerId">openid</param>
        /// <param name="scanEventId">扫码id</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public async Task<Result<List<CloudCards>>> LuckDraw(int consumerId, int scanEventId)
        {
            DateTime dtTime = DateTime.Now;
            List<CloudCards> awardList = new List<CloudCards>();
            try
            {
                var scanEvent = ScanEventBLL.Instance.GetModel(scanEventId);
                if (scanEvent == null || scanEvent.FailScanTime < DateTime.Now || scanEvent.IsReceive == true)
                {
                    _fileLog.Error("CloudCardApiController | LuckDraw | 卡劵已领取,或者已经过了领取时间 , ConsumerId:" + consumerId);
                    return new Result<List<CloudCards>>
                    {
                        Status = false,
                        Message = "扫码记录错误",
                        Data = null,
                        StatusCode = (int)CommonEnum.ApiStatusCode.系统错误
                    };
                }
                if (consumerId != scanEvent.ConsumerId)
                {
                    _fileLog.Error("CloudCardApiController | LuckDraw | 卡卷抽奖人信息不符.仅限扫码人领取! ");
                    return new Result<List<CloudCards>>
                    {
                        Status = false,
                        Message = "卡卷抽奖人信息不符.仅限扫码人领取",
                        Data = null,
                        StatusCode = (int)CommonEnum.ApiStatusCode.卡卷抽奖人信息不符仅限扫码人领取
                    };
                }
                if (scanEvent.ScanSource == (int)CloudCardEnum.ScanEventScanSource.可变卡券二维码扫描)
                {
                    var variableQrCode = VariableQrCodeBLL.Instance.GetModelByQrCodeContent(scanEvent.ScanQrContent);//查询可变二维码内容
                    if (variableQrCode == null || variableQrCode.StartTime > dtTime || variableQrCode.EndTime < dtTime)
                    {
                        _fileLog.Error("CloudCardApiController | LuckDraw | 二维码失效,领取失败 ");
                        return new Result<List<CloudCards>>
                        {
                            Status = false,
                            Message = "二维码失效,领取失败",
                            Data = null,
                            StatusCode = (int)CommonEnum.ApiStatusCode.无效二维码
                        };
                    }
                }

                if (scanEvent.ShopId > 0)            //抽奖
                {
                    var award = _cloudCardBll.GetAward(scanEvent);
                    if (award != null) //如果中奖,获取一张别家劵
                    {
                        _fileLog.Info("CloudCardApiController | LuckDraw | " + award.ShopId + "," + scanEvent.Id);
                        award.ScanId = scanEvent.Id;
                        awardList.Add(award);
                    }
                }
                var searchShopRadius = SysConfig != null ? SysConfig.SearchShopRadius : int.MaxValue;
                var otherCard = _cloudCardBll.ThirdOtherCard(scanEvent, searchShopRadius);
                if (otherCard != null)//其他商家卡劵
                {
                    otherCard.ScanId = scanEvent.Id;
                    awardList.Add(otherCard);
                }
                
                if (awardList.Count < 1)//如果没有抽到奖品直接设置为领取状态
                {
                    scanEvent.IsReceive = true;
                    ScanEventBLL.Instance.Update(scanEvent);
                    return new Result<List<CloudCards>>
                    {
                        Status = false,
                        Message = "对不起,未中奖!",
                        Data = null,
                        StatusCode = (int)CommonEnum.ApiStatusCode.未中奖
                    };
                }
                #region 奖品写入数据
                foreach (var t in awardList)
                {
                    var cloudCards = CloudCardsBLL.Instance.GetModel(t.Id);
                    if (cloudCards != null)
                    {
                        #region 修改扫码次数
                        var shopSubsidiaryInfo = ShopSubsidiaryInfoBLL.Instance.GetModelList(string.Format("ShopId={0}", cloudCards.ShopId)).FirstOrDefault();
                        if (shopSubsidiaryInfo == null || shopSubsidiaryInfo.Id < 1 || (shopSubsidiaryInfo.TotalCanSendCard - shopSubsidiaryInfo.AlreadySendCard) < 1)
                        {
                            _fileLog.Info("CloudCardApiController | BatchReceiveCard | 商户余额不足,或者无可发次数,ShopId:" + cloudCards.ShopId);
                        }
                        // 领取卡劵是 扣除 商家或总部 卡卷次数
                        else
                        {
                            if (_cloudCardBll.AddShopSubsidiaryInfo(shopSubsidiaryInfo))
                                _cloudCardBll.AddUserCard(cloudCards.Id, scanEvent.ConsumerId, scanEvent.Latitude, scanEvent.Longitude, cloudCards.ShopId, scanEvent.ShopId);
                        }
                        #endregion

                    }
                    scanEvent.IsReceive = true;
                    ScanEventBLL.Instance.Update(scanEvent);
                }
                #endregion
                return new Result<List<CloudCards>>
                {
                    Status = true,
                    Message = "Success",
                    Data = awardList,
                    StatusCode = (int)CommonEnum.ApiStatusCode.成功
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ThirdController | LuckDraw | Exception " + ex.Message + ex.StackTrace);
                return new Result<List<CloudCards>>
                 {
                     Status = false,
                     Message = ex.Message,
                     Data = null,
                     StatusCode = (int)CommonEnum.ApiStatusCode.系统错误
                 };
            }
        }
        #endregion

        #region 根据unionid获取优惠券
        /// <summary>
        /// 根据unionid获取优惠券列表
        /// </summary>
        /// <param name="cardStatus">卡卷状态(0未使用1已核销2转赠中3已转赠4售卖中5已售卖)</param>
        /// <param name="mcId">mcId</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="unionid">unionid</param>
        /// <param name="verifyCode">(cardStatus+mcId+mcId+pageIndex+longitude+latitude) Encrypt加密</param>
        /// <returns>Result</returns>
        [HttpPost]
        public Result<List<UserCard>> CloudCardList(int cardStatus, string mcId, int pageIndex, string unionid, string verifyCode)
        {
            var checkResult = CheckPermission("ThirdController | CloudCardList");
            if (!checkResult.Status)
            {
                return new Result<List<UserCard>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            var strSouceToEncode = cardStatus + mcId + pageIndex.ToString() + unionid;
            var strLocalEncodeResult = EncryptionLib.Encrypt(strSouceToEncode, Encoding.UTF8);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("ThirdController | CloudCardList | Error: Invalid verify code.");
                return new Result<List<UserCard>>
                {
                    Status = false,
                    Message = "Invalid verify code",
                    Data = null
                };
            }
            try
            {
                var wechatUserInfo = GetMxApiWechatUserInfoByuinionId(unionid, mcId);
                if (wechatUserInfo == null)
                {
                    return new Result<List<UserCard>>
                    {
                        Status = false,
                        Message = "无效McId或OPENID",
                        Data = null
                    };
                }
                var consumer = ConsumerBLL.Instance.GetConsumerInfoByMxWechatInfoUserId(wechatUserInfo.WiuId);
                if (consumer == null || consumer.Id < 1)
                {
                    return new Result<List<UserCard>>
                    {
                        Data = null,
                        Message = "用户信息错误",
                        Status = false
                    };
                }
                JsonModel.PageList<UserCard> result = UserCardBLL.Instance.GetUserCardList(pageIndex, PageSize, consumer.Id,
                    cardStatus);
                return new Result<List<UserCard>>
                {
                    Status = true,
                    Message = "Success",
                    Data = result.rows
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ThirdController | CloudCardList | Exception " + ex.Message + ex.StackTrace);
                return new Result<List<UserCard>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }
        #endregion

        #region 蓝剑 扫码次数-抽奖

        /// <summary>
        /// 蓝剑扫码抽奖
        /// </summary>
        /// <param name="openId">openId</param>
        /// <param name="mcId">mcId</param>
        /// <param name="random">随机数</param>
        /// <param name="verifyCode">所有参数相加 Encrypt加密</param>
        [System.Web.Http.HttpPost]
        public Result<LanJianAwards> LanJianCodeDraw(string openId, string mcId, string random, string verifyCode)
        {

            _fileLog.Info(
               "ThirdController | LanJianCodeDraw | Scan Url:api/CloudCardApi/FixedQrCodeDraw?openId=" + openId +
               "&mcId=" + mcId + "&random=" + random + "&verifyCode=" + verifyCode +
               "&verifyCode=" + verifyCode);
            #region 权限和加密验证

            var checkResult = CheckPermission("CloudCardApiController | LanJianCodeDraw");
            if (!checkResult.Status)
            {
                return new Result<LanJianAwards>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            var strSouceToEncode = openId + mcId + random;
            var strLocalEncodeResult = EncryptionLib.Encrypt(strSouceToEncode, Encoding.UTF8);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("CloudCardApiController | LanJianCodeDraw | Error: Invalid verify code.");
                return new Result<LanJianAwards>
                {
                    Status = false,
                    Message = "Invalid verify code",
                    Data = null
                };
            }

            #endregion
            try
            {

                #region 公众号-用户信息验证

                var wechatUserInfo = GetMxApiWechatUserInfo(openId, mcId);
                if (wechatUserInfo == null)
                {
                    return new Result<LanJianAwards>
                    {
                        Status = false,
                        Message = "无效McId或OPENID",
                        Data = null
                    };
                }
                var consumer = ConsumerBLL.Instance.GetConsumerInfoByMxWechatInfoUserId(wechatUserInfo.WiuId);
                if (consumer == null || consumer.Id < 1)
                {
                    _fileLog.Error("CloudCardApiController | LanJianCodeDraw | Error: Invalid consumer.");
                    return new Result<LanJianAwards>
                    {
                        Status = false,
                        Message = "无效用户",
                        Data = null
                    };
                }
                if (!wechatUserInfo.Subscribe) //用户是否关注微信公众号
                {
                    _fileLog.Error("CloudCardApiController | LanJianCodeDraw |未关注公众号 ");
                    return new Result<LanJianAwards>
                    {
                        Status = false,
                        Message = "未关注公众号",
                        Data = null
                    };
                }

                #endregion

                int lanJianDrawRecordCount = LanJianDrawRecordBLL.Instance.GetModelList(" ConsumerId=" + consumer.Id + "").Count();
                int scanEventCount = ScanEventBLL.Instance.GetModelList(" ConsumerId=" + consumer.Id + "").Count();
                if ((scanEventCount - lanJianDrawRecordCount) < 1)
                {
                    return new Result<LanJianAwards>
                    {
                        Status = false,
                        Message = "你没有可抽奖次数",
                        Data = null
                    };
                }
                var lanJianAwardsList =
                    LanJianAwardsBLL.Instance.GetModelList(
                        string.Format(" IsOpen='{0}' and (TotalQuantity -SendQuantity) >1", true));
                if (lanJianAwardsList.Count > 0)
                {
                    Random rd = new Random();
                    int m = -1;
                    if (lanJianAwardsList.Count > 0) //如果不等于空取出一个随机卡劵
                    {
                        m = rd.Next(0, lanJianAwardsList.Count);
                    }
                    if (m > -1)
                    {
                        LanJianDrawRecordBLL.Instance.Add(new LanJianDrawRecord()
                        {
                            AddTime = DateTime.Now,
                            ConsumerId = consumer.Id,
                            LanJianAwardId = lanJianAwardsList[m].Id,
                            IsDelete = false
                        });
                        lanJianAwardsList[m].SendQuantity = lanJianAwardsList[m].SendQuantity + 1;
                        LanJianAwardsBLL.Instance.Update(lanJianAwardsList[m]);
                        return new Result<LanJianAwards>
                        {
                            Status = true,
                            Message = "Success",
                            Data = lanJianAwardsList[m]
                        };
                    }
                    else
                    {
                        return new Result<LanJianAwards>
                        {
                            Status = false,
                            Message = "对不起,未中奖",
                            Data = null
                        };
                    }
                }
                return new Result<LanJianAwards>
                {
                    Status = false,
                    Message = "对不起,未中奖",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ThirdController | LanJianCodeDraw | Exception " + ex.Message + ex.StackTrace);
                return new Result<LanJianAwards>
                  {
                      Status = false,
                      Message = ex.Message,
                      Data = null
                  };
            }
        }

        #endregion

        #region 蓝剑 扫码次数-抽奖记录

        /// <summary>
        /// 蓝剑 扫码次数-抽奖记录
        /// </summary>
        /// <param name="openId">openId</param>
        /// <param name="mcId">mcId</param>
        /// <param name="random">随机数</param>
        /// <param name="verifyCode">所有参数相加 Encrypt加密</param>
        public Result<List<LanJianDrawRecord>> LanJianDrawRecord(string openId, string mcId, string random, string verifyCode)
        {
            #region 权限和加密验证
            var checkResult = CheckPermission("CloudCardApiController | LanJianDrawRecord");
            if (!checkResult.Status)
            {
                return new Result<List<LanJianDrawRecord>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            var strSouceToEncode = openId + mcId + random;
            var strLocalEncodeResult = EncryptionLib.Encrypt(strSouceToEncode, Encoding.UTF8);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("CloudCardApiController | LanJianDrawRecord | Error: Invalid verify code.");
                return new Result<List<LanJianDrawRecord>>
                {
                    Status = false,
                    Message = "Invalid verify code",
                    Data = null
                };
            }

            #endregion
            try
            {

                #region 公众号-用户信息验证
                var wechatUserInfo = GetMxApiWechatUserInfo(openId, mcId);
                if (wechatUserInfo == null)
                {
                    return new Result<List<LanJianDrawRecord>>
                    {
                        Status = false,
                        Message = "无效McId或OPENID",
                        Data = null
                    };
                }
                var consumer = ConsumerBLL.Instance.GetConsumerInfoByMxWechatInfoUserId(wechatUserInfo.WiuId);
                if (consumer == null || consumer.Id < 1)
                {
                    _fileLog.Error("CloudCardApiController | LanJianDrawRecord | Error: Invalid consumer.");
                    return new Result<List<LanJianDrawRecord>>
                    {
                        Status = false,
                        Message = "无效用户",
                        Data = null
                    };
                }
                if (!wechatUserInfo.Subscribe) //用户是否关注微信公众号
                {
                    _fileLog.Error("CloudCardApiController | LanJianDrawRecord |未关注公众号 ");
                    return new Result<List<LanJianDrawRecord>>
                    {
                        Status = false,
                        Message = "未关注公众号",
                        Data = null
                    };
                }
                #endregion
                var lanJianDrawRecordList = LanJianDrawRecordBLL.Instance.GetModelList("");
                return new Result<List<LanJianDrawRecord>>
                {
                    Status = true,
                    Message = "Success",
                    Data = lanJianDrawRecordList
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ThirdController | LanJianDrawRecord | Exception " + ex.Message + ex.StackTrace);
                return new Result<List<LanJianDrawRecord>>
                 {
                     Status = false,
                     Message = ex.Message,
                     Data = null
                 };
            }
        }

        #endregion

        /// <summary>
        /// 获取openid蓝剑可抽奖次数
        /// </summary>
        /// <param name="openId">openId</param>
        /// <param name="mcId">mcId</param>
        /// <param name="random">随机数</param>
        /// <param name="verifyCode">加密code</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public Result<string> LanJianDrawNumber(string openId, string mcId, string random, string verifyCode)
        {
            #region 权限和加密验证
            var checkResult = CheckPermission("ThirdController | LanJianDrawNumber");
            if (!checkResult.Status)
            {
                return new Result<string>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            var strSouceToEncode = openId + mcId + random;
            var strLocalEncodeResult = EncryptionLib.Encrypt(strSouceToEncode, Encoding.UTF8);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("ThirdController | LanJianDrawNumber | Error: Invalid verify code.");
                return new Result<string>
                {
                    Status = false,
                    Message = "Invalid verify code",
                    Data = null
                };
            }

            #endregion

            try
            {
                #region 公众号-用户信息验证
                var wechatUserInfo = GetMxApiWechatUserInfo(openId, mcId);
                if (wechatUserInfo == null)
                {
                    return new Result<string>
                    {
                        Status = false,
                        Message = "无效McId或OPENID",
                        Data = null
                    };
                }
                var consumer = ConsumerBLL.Instance.GetConsumerInfoByMxWechatInfoUserId(wechatUserInfo.WiuId);
                if (consumer == null || consumer.Id < 1)
                {
                    _fileLog.Error("ThirdController | LanJianDrawNumber | Error: Invalid consumer.");
                    return new Result<string>
                    {
                        Status = false,
                        Message = "无效用户",
                        Data = null
                    };
                }
                if (!wechatUserInfo.Subscribe) //用户是否关注微信公众号
                {
                    _fileLog.Error("ThirdController | LanJianDrawNumber |未关注公众号 ");
                    return new Result<string>
                    {
                        Status = false,
                        Message = "未关注公众号",
                        Data = null
                    };
                }
                #endregion
                int lanJianDrawRecordCount = LanJianDrawRecordBLL.Instance.GetModelList(" ConsumerId=" + consumer.Id + "").Count();
                int scanEventCount = ScanEventBLL.Instance.GetModelList(" ConsumerId=" + consumer.Id + "").Count();
                return new Result<string>
                {
                    Status = true,
                    Message = "Success",
                    Data = (scanEventCount - lanJianDrawRecordCount).ToString()
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ThirdController | LanJianDrawRecord | Exception " + ex.Message + ex.StackTrace);
                return new Result<string>
                            {
                                Status = false,
                                Message = ex.Message,
                                Data = null
                            };
            }
        }

        #region 根据时间获取第三方请求的扫码数据

        /// <summary>
        /// 根据时间获取第三方请求的扫码数据
        /// </summary>
        /// <param name="starTime"></param>
        /// <param name="endTime"></param>
        /// <param name="random"></param>
        /// <param name="verifyCode"></param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public Result<List<ScanEventDto>> GetScanEventList(DateTime starTime, DateTime endTime, string random, string verifyCode)
        {
            #region 权限和加密验证
            var checkResult = CheckPermission("ThirdController | GetScanEventList");
            if (!checkResult.Status)
            {
                return new Result<List<ScanEventDto>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            var strSouceToEncode = starTime.ToString("yyyy-MM-dd") + endTime.ToString("yyyy-MM-dd") + random;
            var strLocalEncodeResult = EncryptionLib.Encrypt(strSouceToEncode, Encoding.UTF8);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("CloudCardApiController | GetScanEventList | Error: Invalid verify code.  strLocalEncodeResult=" + strLocalEncodeResult + "   starTime.ToShortDateString()=" + starTime.ToShortDateString());
                return new Result<List<ScanEventDto>>
                {
                    Status = false,
                    Message = "Invalid verify code",
                    Data = null
                };
            }
            #endregion
            try
            {
                var scanEventList = ScanEventBLL.Instance.GetList((int)CloudCardEnum.ScanEventScanSource.第三方接口请求, starTime, endTime, "  Longitude is not null");
                if (scanEventList != null && scanEventList.Count > 0)
                {
                    return new Result<List<ScanEventDto>>
                    {
                        Status = true,
                        Message = "Success",
                        Data = scanEventList
                    };
                }
                return new Result<List<ScanEventDto>>
                {
                    Status = false,
                    Message = "暂无数据",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("ThirdController | GetScanEventList | Exception " + ex.Message + ex.StackTrace);
                return new Result<List<ScanEventDto>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
            return null;

        }
        #endregion
    }
}